package com.demo.commons.exceptions;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.io.IOException;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler
    public void exceptionHandle(Exception e, HttpServletResponse response) throws Exception {
        logger.debug("init exception handle");

        if (e instanceof HttpStatusCodeException) {

            try {
                response.sendError(((HttpStatusCodeException) e).getStatusCode().value(), e.getMessage());
            } catch (IOException exception) {
                logger.error("Unexpected exception", exception);

                throw exception;
            }

        } else {

            throw e;
        }
    }
}
